# coding=utf-8
# author:hhu_zym(qq:1045797922)
# 动脑学院VIP学员

'''
主要是练习装饰器,和多线程,多进程的使用

使用装饰器增强完成1-999999所有奇数和计算10次
   1.使用普通方法
   2.使用多线程
   3.使用多进程
   4.采用线程池完成计算
   5.采用进程池完成计算
'''
from multiprocessing import Pool,cpu_count
from multiprocessing.dummy import Pool as threadpool
import time

# 装饰器函数
def c_time(func):
    def inner(num):
        time1=time.time()
        func(num)
        time2=time.time()
        print('计算花费的时间为%s' % str(time2-time1))
    return inner

# 1.使用普通方法
# @c_time
# def c_10time(num):
#     for i in range(10):
#         sum(range(1,num,2))

# if __name__=='__main__':
#     c_10time(1000000)  # 计算花费的时间为0.20514345169067383

# 2.使用多线程
# from threading import Thread,current_thread
# def c_10time(num):
#     for i in range(10):
#         sum(range(1,num,2))
#
# @c_time
# def thread_10time(num):
#     for item in range(10):
#         thread=Thread(target=c_time,args=(num,))
#         thread.start()
#         thread.join()
#
# if __name__=='__main__':
#     thread_10time(1000000)  # 计算花费的时间为0.001990079879760742

# 3.使用多进程
# from multiprocessing import Process,Pool
# def c_10time(num):
#     for i in range(10):
#         sum(range(1,num,2))
#
# @c_time
# def process_10time(num):
#     for item in range(10):
#         pro=Process(target=c_time,args=(num,))
#         pro.start()
#         pro.join()
#
# if __name__=='__main__':
#     process_10time(1000000)  # 计算花费的时间为2.594836473464966

# 4.采用线程池完成
# 计算
# def c_10time(num):
#     for i in range(10):
#         sum(range(1,num,2))
#
# @c_time
# def thread_10time(num):
#     pools=threadpool(cpu_count())
#     for i in range(10):
#         pools.apply_async(c_10time,(num,))
#     pools.close()
#     pools.join()
#
# if __name__=='__main__':
#     thread_10time(1000000)  # 计算花费的时间为2.0404529571533203

# 5.采用进程池完成计算
def c_10time(num):
    for i in range(10):
        sum(range(1,num,2))

@c_time
def process_10time(num):
    pools=Pool(cpu_count())
    for i in range(10):
        pools.apply_async(c_10time,(num,))
    pools.close()
    pools.join()

if __name__=='__main__':
    process_10time(1000000)  # 计算花费的时间为1.2738914489746094